#-*- coding:utf-8 -*-  
'''
Created on 2011-11-2

@author: Botao Wu
'''
import weakref
import new

class ref(object):
    '''能够封装任何可调用体，特别是被绑定方法，而且被绑定
    方法仍然能被回收处理。与此同时，提供一个普通的弱引用接口'''
    def __init__(self, fn):
        try:
            #试图获取对象，函数和类
            o, f, c = fn.im_self, fn.im_func, fn.im_class
        except AttributeError:
            self._obj = None
            self._func = fn
            self._class = None
        else:
            if o is None:
                self._obj = None
            else:
                self._obj = weakref.ref(o)
            self._func = f
            self._class = c
            
    def __call__(self):
        if self.obj is None:
            return self._func
        elif self._obj() is None:
            return None
        return new.instancemethod(self._func, self.obj(), self._class)
    

class C(object):
    
    def f(self):
        print 'Hello'
        
    def __del__(self):
        print 'C dying'
        
if __name__ == '__main__':
    c = C()
#    cf = c.f()
#    del c
#    del cf
    cf = weakref.ref(c.f)
    print cf
    
#    cf = ref(c.f)
#    print cf
#    del c
#    print cf
